package Concurrency2.Chapter09_CallBackPattern;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * Instruction：异步阻塞 - 使用FutureTask方式实现回调
 * Callable(Interface) --> RunnableFuture(Interface) --> FutureTask : Callable属性, run方法中
 * Author：@author MaLi
 */
public class CallBack_FutureTask {
    public static class HotWater implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            System.out.println("洗水壶");
            System.out.println("灌水");
            System.out.println("开火");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("水烧开了");
            return true;
        }
    }

    //清洗任务
    public static class WashGlasses implements Callable<Boolean> {

        @Override
        public Boolean call() {
            System.out.println("洗茶壶");
            System.out.println("洗茶杯");
            System.out.println("拿茶叶");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("清洗完成");
            return true;
        }
    }

    public static void main(String[] args) {
        FutureTask<Boolean> hTask = new FutureTask<>(new HotWater());
        FutureTask<Boolean> wTask = new FutureTask<>(new WashGlasses());
        Thread hThread = new Thread(hTask);
        Thread wThread = new Thread(wTask);
        hThread.start();
        wThread.start();
        try {
            Boolean hResult = hTask.get();
            Boolean wGet = wTask.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println("主线程继续执行: 泡茶喝...");
    }
}
